//
//  HMHomeTableViewController.swift
//  weibo28
//
//  Created by 范英强 on 16/3/23.
//  Copyright © 2016年 范英强. All rights reserved.
//

import UIKit
import AFNetworking
// cell标示
private let cellIdentifier = "cellIdentifier"
class HMHomeTableViewController: HMVisitorTableViewController {
    // 保存首页数据
    var statusList: [HMStatus] = [HMStatus]()
    
    let refreshView = UIRefreshControl()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !isLogin{
            visitorView?.setVisitorInfo(nil, title: nil)
            return
        }
        setTableViewInfo()
        loadData(activityView.isAnimating())
    }
    
    // MARK: - 设置tableview相关属性
    func setTableViewInfo(){
        tableView.registerClass(HMStatusCell.self, forCellReuseIdentifier: cellIdentifier)
        
        // 设置cell高度
       // tableView.rowHeight = 300
        // 设置tableView 的cell的预估行高 (当我们创建的cell的时候 我们设置一个预估行高)
        tableView.estimatedRowHeight = 200
        
        // 隐藏分割线
        tableView.separatorStyle = .None
        
        
        refreshView.addTarget(self, action: "refreshViews", forControlEvents: UIControlEvents.ValueChanged)
        
        tableView.addSubview(refreshView)
        
        
        tableView.tableFooterView = activityView

    }
    
    func refreshViews(){
        self.loadData(self.activityView.isAnimating())

        
        
    }
    
    // MARK: - 懒加载控件
    private lazy var activityView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge);
        view.color = UIColor.redColor()
        return view
    }()
    
    
    // MARK: - 请求数据
    func loadData(isPullup: Bool){
        var maxId:Int64 = 0
        var sinceId:Int64 = 0
        
        if isPullup{

            maxId = statusList.last?.id ?? 0
            
            if maxId > 0{
                maxId = maxId - 1
            }
            
        }else{
            sinceId = statusList.first?.id ?? 0
        }
        
        
        
        
        // 请求的urlString
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
        // 请求参数
        let params = [
            "access_token": HMUserAccountTools.sharedTools.accessToken!,
            "max_id":"\(maxId)",
            "since_id":"\(sinceId)"
        ]
        
        let manager = AFHTTPSessionManager()
        
        manager.GET(urlString, parameters: params, progress: nil, success: { (_, response) -> Void in
            
            
            guard let dict = response as? [String: AnyObject] else{
                print("返回来的数据不是一个字典")
                return
            }
            
            guard let array = dict["statuses"]  as? [[String: AnyObject]] else{
                print("不是数据")
                return
            }
         
            // 临时数组
            var tempArray:[HMStatus] = [HMStatus]()
            // 遍历数据转模型
            for dict in array {
                let status = HMStatus(dict: dict)
                tempArray.append(status)
            }
            
            if isPullup{
                self.statusList = self.statusList + tempArray
            }else{
                self.statusList = tempArray + self.statusList
            }
            print("请求回来\(tempArray.count)条数据")
            
            // 得到数据后 刷新tableView********
            self.tableView.reloadData()
            self.endRefreshing()
            }) { (_, error) -> Void in
                print("错误\(error)")
        }
    }
    
    func endRefreshing(){
        self.activityView.stopAnimating()
        self.refreshView.endRefreshing()
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(5 * NSEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
//            self.activityView.stopAnimating()
//            self.refreshView.endRefreshing()
//            
//        }
//        
        
        
    }

}

// MARK: - tableView dataSource Delegate
extension HMHomeTableViewController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! HMStatusCell
        cell.status = statusList[indexPath.row]
        return cell
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

        if indexPath.row == statusList.count - 1 && !activityView.isAnimating(){
            // 在开始动画对吧
            
            activityView.startAnimating()
            self.loadData(self.activityView.isAnimating())
            
            
        }
        
    }
}
